<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\Album;
use App\Model\Photo;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AlbumController extends Controller
{
    public function index(Request $request, Album $album)
    {
        $uid = $request->user()->id;
        $albums = $album->where('uid', $uid)->get();
        $data = [];
        foreach ($albums as $album) {
            $data[] = [
                'id' => $album->id,
                'name' => $album->name,
                'cover' => $album->cover
            ];
        }
        return $this->renderJson($data);
    }

    /**
     * 单个相册照片
     * @param int $id
     * @param Photo $photo
     * @return Response
     */
    public function show($id, Photo $photo)
    {
        $uid = Auth::id();
        $photos = $photo->where(['uid' => $uid, 'aid' => $id])->get();
        $data = [];
        foreach ($photos as $photo) {
            $data[] = [
                'id' => $photo->id,
                'url' => $photo->url
            ];
        }
        return $this->renderJson($data);
    }

    public function store(Request $request, Album $album)
    {
        //自动验证
        $this->validate($request, [
            'name' => 'required|string|min:2|max:20'
        ], [
            'required' => ':attribute不能为空',
            'min' => ':attribute名称长度不得少于:min个字',

            'max' => ':attribute名称长度不得大于:max个字'
        ], [
            'name' => '相册名'
        ]);
        $data = [
            'uid' => $request->user()->id,
            'name' => $request->input('name')
        ];
        if ($album->create($data)) {
            return $this->success('添加相册成功');
        }
        return $this->error('添加失败');
    }

    public function destroy($id, Album $album, Photo $photo)
    {
        $album = $album->findOrFail($id);
        try {
            DB::beginTransaction();
            $album->delete();
            $photo->where(['uid'=>Auth::id(),'aid'=>$id])->delete();
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }
}
